package com.beijiteshop.libcommon.base.fragment

import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.beijiteshop.libcommon.R
import com.beijiteshop.libcommon.login.UserInfoUtil
import com.beijiteshop.libcommon.view.LoadingDialog

/**
 * 基类Fragment
 */
abstract class BaseFragment(layoutId: Int) : Fragment(layoutId){

    private var mLoadingDialog: LoadingDialog? = null


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view)
        initData()
        initEvent()
    }

    abstract fun initView(view: View)

    abstract fun initData()

    abstract fun initEvent()

    /**
     * 扩展用于liveData便捷写法的函数
     * [block]liveData对象，响应change变化的逻辑块
     */
    protected fun <T : Any?> MutableLiveData<T>.observeKt(block: (T?) -> Unit) {
        this.observe(viewLifecycleOwner, Observer {
            block(it)
        })
    }

    protected fun showToast(text: String){
        val toast = Toast.makeText(this.requireContext(),text,Toast.LENGTH_SHORT)
        toast.show()
    }

    protected fun showToastInCenter(text: String){
        val toast = Toast.makeText(requireContext(),text,Toast.LENGTH_SHORT)
        toast.setGravity(Gravity.CENTER,0,0)
        toast.show()
    }

    protected fun showNetErrorToast(text: String? = null){
        Toast.makeText(this.requireContext(),text?:resources.getString(R.string.state_network_error),Toast.LENGTH_SHORT).show()
    }

    protected fun isUserLogin(): Boolean{
        return UserInfoUtil.getInstance().isLogin()
    }

    protected fun showLoading(text: String? = null){
        mLoadingDialog = LoadingDialog.showDialog(childFragmentManager,text)
    }

    protected fun hideLoading(){
        mLoadingDialog?.dismissDialog()
    }
}